<?php
class SEARCH{
    private $db;
    private $per_page=3;
    private $table;
    public $pager;
    function __construct($db){
        $this->db=$db;
        $this->table="weixin";
    }
    function lists($keywords){//获取首页产品列表
        $result=$this->_lists_data($keywords);
        return $this->_filter_result($result);
    }
    
    ///以下为私有方法
    private function _page($where){
        $data_count=$this->_getTotal($where);
        //分页
        $records_per_page = $this->per_page;
        $total_pages = ceil($data_count/$records_per_page);
        
        $pager = new pager(array('total'=>$data_count,'perpage'=>$records_per_page));
        $pagenum = intval($_GET['pagenum'])<1?1:intval($_GET['pagenum']);
        $pagenum = ($pagenum>$total_pages)?$total_pages:$pagenum;
        $pagenum = ($pagenum<1)?1:$pagenum;
        $this->offset = ($pagenum-1)*$records_per_page;
        return $pager;
    }
    private function _getTotal($where){
        //得到总数
        $data_count_req = $this->db->query_first("SELECT count(wx_id) as t FROM ".$this->table." where 1=1 $where");
        $data_count = $data_count_req['t'];
        return $data_count;
    }
    private function _lists_data($where=array()){//获取产品列表
        $where_str=$this->_search_keywords($where);
        
        $this->pager=$this->_page($where_str);
        
        $sql="select * from ".$this->table." where 1=1  and status=1 $where_str  order by sort desc,add_time desc";
        $result=$this->db->query_all($sql);
        
        return $result;
    }
    private function _filter_result($result){//对返回的结果进行处理
        
        return $result;
    }
    
    private function _search_keywords($keywords){//处理搜索关键字
        if(empty($keywords)){
            return ;
        }
        $keywords=array_values(array_unique(array_filter(explode(' ',$keywords))));
        foreach ($keywords as $key=>$value){
            $keywords[$key]="CONCAT(wx_title,keyword,contents) like '%$value%' ";
        }
        $where_str=  implode(" or ",$keywords);
        $where_str=" and ($where_str)";
        return $where_str;
    }
}